package com.ywu.common.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ywu.common.mapper.YwuBeanMapper;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @ClassName GsonUtils
 * @Description gson工具类
 * @Author GroundDemo
 * @Date 2023/11/12 19:55
 * @Version 1.0
 **/
public class GsonUtils {

    private static final Gson gson;

    static {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
        gson = gsonBuilder.create();
    }

    public static String serialize(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T deserialize(String jsonInfo, Class<T> type) {
        return gson.fromJson(jsonInfo, type);
    }

    public static <T> List<T> deserializeList(String jsonInfo, Class<T> clazz) {
        Type listType = new TypeToken<List<T>>() {}.getType();
        List<T> gsonRes = gson.fromJson(jsonInfo, listType);
        return YwuBeanMapper.mapList(gsonRes, clazz);
    }

}
